package com.sky.sentinel.config;

import com.alibaba.csp.sentinel.annotation.aspectj.SentinelResourceAspect;
import com.alibaba.csp.sentinel.slots.block.RuleConstant;
import com.alibaba.csp.sentinel.slots.block.degrade.DegradeRule;
import com.alibaba.csp.sentinel.slots.block.degrade.DegradeRuleManager;
import com.alibaba.csp.sentinel.slots.block.flow.FlowRule;
import com.alibaba.csp.sentinel.slots.block.flow.FlowRuleManager;
import com.alibaba.fastjson.JSONObject;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.ArrayList;
import java.util.List;

@Configuration
public class SentinelConfig {

    @Bean
    public SentinelResourceAspect sentinelResourceAspect() {
        return new SentinelResourceAspect();
    }


    /**
     *  限流规则
     *  {"resource":"flowRule","controlBehavior":0,"count":5.0,"grade":1,"limitApp":"default","strategy":0}
     * 参考文档：http://www.imooc.com/article/289345、
     * https://github.com/alibaba/Sentinel/wiki/%E5%A6%82%E4%BD%95%E4%BD%BF%E7%94%A8#%E8%A7%84%E5%88%99%E7%9A%84%E7%A7%8D%E7%B1%BB
     * @param flowRules
     */
    public static void initFlowRule(String flowRules) {
        JSONObject json = JSONObject.parseObject(flowRules);
        List<FlowRule> rules = new ArrayList<>();
        FlowRule rule = new FlowRule();
        rule.setResource(json.getString("resource"));
        // 设置阈值
        rule.setCount(json.getInteger("count"));
        // 限流阈值类型，QPS 模式（1）或并发线程数模式（0）
        rule.setGrade(json.getInteger("grade"));
        rule.setLimitApp(json.getString("limitApp"));
        rule.setStrategy(json.getInteger("strategy"));
        // 流控效果（直接拒绝 / 排队等待 / 慢启动模式），默认：直接拒绝
        rule.setControlBehavior(json.getInteger("controlBehavior"));
        rules.add(rule);
        FlowRuleManager.loadRules(rules);
    }

    /**
     * 降级规则
     * {"resource":"degradeRule","count":1,"grade":0,"limitApp":"default","timeWindow":10}
     * 以上规则的意思是 降级规则degradeRule，相应时间超过1毫秒则直接讲解，降级时间间隔为10秒钟
     * 参考文档：http://www.imooc.com/article/289345、
     * https://github.com/alibaba/Sentinel/wiki/%E5%A6%82%E4%BD%95%E4%BD%BF%E7%94%A8#%E8%A7%84%E5%88%99%E7%9A%84%E7%A7%8D%E7%B1%BB
     * @param flowRules
     */
    public static void initDegradeRule(String flowRules) {
        JSONObject json = JSONObject.parseObject(flowRules);
        List<DegradeRule> rules = new ArrayList<>();
        DegradeRule rule = new DegradeRule();
        rule.setResource(json.getString("resource"));
        // 设置降级规则的时间，单位毫秒
        rule.setCount(json.getInteger("count"));
        // 降级设置分为：0->RT(相应时间ResponseTime)、1->秒级异常比例、2->分钟级异常数
        rule.setGrade(json.getInteger("grade"));
        // 设置降级多长时间，单位秒
        rule.setTimeWindow(json.getInteger("timeWindow"));
        rules.add(rule);
        DegradeRuleManager.loadRules(rules);
    }
}
